package com.zryc.api.filters;

import com.zryc.shop.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Value("${noneed-auth-paths}")
    private String unAuthPaths;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从当前的请求参数(更好的方式时请求头，但是不好测试)中获取一个名为token的参数值
        ServerHttpRequest request = exchange.getRequest();
        //直接判断放行一部分请求，例如：登录
        String path =request.getURI().getPath();//获取当前请求的URI路径
        if (unAuthPaths.contains(path)){//如果当前的访问路径包含在无需认证的路径列表则直接放行
            return chain.filter(exchange);//不进行token解析认证，直接放行
        }
        String token = request.getHeaders().getFirst("Authorization");
        //认证失败的原因1、没登陆token为空2、token是伪造的,解析会失败 3、token过期了
        try{
            String[] tokenInfo=token.split(" ");//用空格将请求头中获取的token分成两端
            Claims claims= JwtUtils.parseJwt(tokenInfo[1]);
            return chain.filter(exchange);//令牌解析成功后，表示用户具备访问权限，过滤器链继续向下执行fffff
        }catch (Exception e){
            e.printStackTrace();
            //令牌的解析出错了
            System.out.println("当前用户不具备访问权限！");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//设置响应状态码为未授权 401
            return exchange.getResponse().setComplete();//设置当前请求完成
        }
    }

    @Override
    public int getOrder() {//返回一个代表过滤器执行优先级的证书，越小表示优先级越高
        return 0;
    }
}
